﻿using AntdUI.Svg;
using CodeGenerator.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Policy;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeGenerator
{
    internal static class Program
    {
        public static Form form;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 订阅全局异常事件
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

            Application.Run(new Main());
        }

        private static async void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            var updateDir = CommonUtil.GenFullPath("tmp/update_app");
            var runPath = @".\updateFile.bat";
            var runExePath = Assembly.GetExecutingAssembly().Location;
            runExePath = $@".\{Path.GetFileName(runExePath)}";
            if (!Directory.Exists(updateDir))
            {
                return;
            }
            // 创建一个新的进程
            Process process = new Process();
            // 设置进程启动信息
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = $"/c \"{runPath}\" {runExePath}";
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            // 启动进程
            process.Start();

        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            var ex = e.Exception;
            ShowErrorModal(ex.Message);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // 处理未处理的异常
            var ex = (Exception)e.ExceptionObject;
            ShowErrorModal(ex.Message);
        }
        static void ShowErrorModal(string msg)
        {
            if (form == null)
            {
                MessageBox.Show(msg, @"错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(form, "错误", msg, AntdUI.TType.Error)
                {
                    CancelText = null,
                    OkText = "确定"
                });
            }
        }
    }
}
